var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var _limitMenu = system.MENULIMIT.STOCK26;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'stock/data/type_level_stock';
var _height = $(parent).height()-328,_width = $(parent).width()-192;
var api = frameElement.api;
if(api){
	_height = $(defaultPage).height()-348,_width = $(defaultPage).width()-222;
}
var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:true,module:'stock'},
			width : 500,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				selectShops = selected;
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].sp_code);
					names.push(selected[i].sp_name);
				}
				$("#shopCodes").val(codes.join(","));
				$("#shop_name").val(names.join(","));
			},
			cancel:true
		});
	},
	doQueryBrand : function(){
		commonDia = $.dialog({
			title : '选择品牌',
			content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].bd_code);
					names.push(selected[i].bd_name);
				}
				$("#bd_code").val(codes.join(","));
				$("#bd_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryType : function(){
		commonDia = $.dialog({
			title : '选择类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 300,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].tp_code);
					names.push(selected[i].tp_name);
				}
				$("#tp_code").val(codes.join(","));
				$("#tp_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryProduct : function(){
		commonDia = $.dialog({
			title : '选择商品',
			content : 'url:'+config.BASEPATH+'base/product/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#pd_code").val(selected.pd_code);
				$("#pd_name").val(selected.pd_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#pd_code").val(selected.pd_code);
					$("#pd_name").val(selected.pd_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	queryChildType:function(Code){
		var params = {};
		params.pd_code = $("#pd_code").val();
		params.pd_name = $("#pd_name").val();
		params.bd_name = $("#bd_name").val();
		params.bd_code = $("#bd_code").val();
		params.shop_name = $("#shop_name").val();
		params.shopCodes = $("#shopCodes").val();
		params.pd_season = $("#pd_season").val();
		params.pd_year = $("#pd_year").val();
        $.dialog({
            id:'',
            title:false,
            data:params,
            max: false,
            min: false,
            fixed:false,
            drag:false,
            resize:false,
            lock:false,
            content:'url:'+config.BASEPATH+'stock/data/to_type_level_stock/'+Code,
            close:function(){
            }
        }).max();
    },
	formatData :function(val, opt, row){
		if($.trim(val) == ""){
			return "";
		}
		if(row.tp_code == "合计"){
			return val;
		}
		if(row.project == '数量'){
			return val;
		}else if(row.project == '金额'){
			return PriceLimit.formatMoney(val);
		}
		return '';
	}
};

var allShops = [];
var selectShops = [];
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		if("0" == $("#tp_upcode").val()){
			$("#btn_close").hide();
		}
		this.initParams();
		this.getAllShop();
		this.initSeason();
		this.initYear();
	},
	initParams:function(){
		if(api == undefined){
			return;
		}
		var params = api.data;
		$("#pd_code").val($.trim(params.pd_code));
		$("#pd_name").val($.trim(params.pd_name));
		$("#bd_name").val($.trim(params.bd_name));
		$("#bd_code").val($.trim(params.bd_code));
		$("#shop_name").val($.trim(params.shop_name));
		$("#shopCodes").val($.trim(params.shopCodes));
		$("#pd_season").val($.trim(params.pd_season));
		$("#pd_year").val($.trim(params.pd_year));
		if($.trim(params.shopCodes) != ""){
			var codes = params.shopCodes.split(",");
			var names = params.shop_name.split(",");
			for (var i = 0; i < codes.length; i++) {
				var item = {};
				item.sp_code = codes[i];
				item.sp_name = names[i];
				selectShops.push(item);
			}
		}
	},
	initSeason:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"base/dict/list?dtl_upcode=KEY_SEASON",
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.data != "" && data.data.length > 0){
					var seasons = data.data;
					seasons.unshift({dtl_code:"",dtl_name:"全部"});
					$('#span_pd_season').combo({
						value : 'dtl_code',
						text : 'dtl_name',
						width : 207,
						listHeight : 300,
						listId : '',
						defaultSelected : 0,
						editable : false,
						callback : {
							onChange : function(data) {
								if(data.dtl_code != ""){
									$("#pd_season").val(data.dtl_name);
								}else{
									$("#pd_season").val("");
								}
							}
						}
					}).getCombo().loadData(seasons,["dtl_name",$("#pd_season").val(),0]);
				}
			}
		 });
	},
	initYear:function(){
		var currentYear = new Date().getFullYear();
		var data = [
		    {Code:"",Name:"全部"},
			{Code:""+parseInt(currentYear+1)+"",Name:""+parseInt(currentYear+1)+""},
			{Code:""+parseInt(currentYear)+"",Name:""+parseInt(currentYear)+""},
			{Code:""+parseInt(currentYear-1)+"",Name:""+parseInt(currentYear-1)+""},
			{Code:""+parseInt(currentYear-2)+"",Name:""+parseInt(currentYear-2)+""},
			{Code:""+parseInt(currentYear-3)+"",Name:""+parseInt(currentYear-3)+""},
			{Code:""+parseInt(currentYear-4)+"",Name:""+parseInt(currentYear-4)+""},
			{Code:""+parseInt(currentYear-5)+"",Name:""+parseInt(currentYear-5)+""}
		];
		$('#span_pd_year').combo({
			value: 'Code',
			text: 'Name',
			width :206,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: false,
			callback:{
				onChange: function(data){
					$("#pd_year").val(data.Code);
				}
			}
		}).getCombo().loadData(data,["Code",$("#pd_year").val(),0]);
	},
	getAllShop:function(){/*获取所有店铺数据*/
		$.ajax({
			type:"POST",
			async:false,
			url:config.BASEPATH+"base/shop/up_sub_list?sidx=sp_code&sord=asc",
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					allShops=data.data;
				}
			}
		});
	},
	gridTotal:function(){
    	var grid = $('#grid');
		var footerData = {tp_code:'合计'};
		var ids = $("#grid").getDataIDs();
		var amountTotal = {};
		var moneyTotal = {};
		if(selectShops != null && selectShops.length > 0){
			for (var i = 0; i < selectShops.length; i++) {
				amountTotal[selectShops[i].sp_code] = 0;
				moneyTotal[selectShops[i].sp_code] = 0;
			}
			amountTotal["total"] = 0;
			moneyTotal["total"] = 0;
		}else{
			for (var i = 0; i < allShops.length; i++) {
				amountTotal[allShops[i].sp_code] = 0;
				moneyTotal[allShops[i].sp_code] = 0;
			}
			amountTotal["total"] = 0;
			moneyTotal["total"] = 0;
		}
		for (var i = 0; i < ids.length; i++) {
			var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			if(rowData.project == '数量'){
				for(var key in amountTotal){
					if($.trim(rowData[key]) != ""){
						amountTotal[key] = amountTotal[key] + parseInt(rowData[key]);
					}
				}
			}else if(rowData.project == '金额'){
				for(var key in moneyTotal){
					if($.trim(rowData[key]) != ""){
						moneyTotal[key] = moneyTotal[key] + parseFloat(rowData[key]);
					}
				}
			}
		}
		for(var key in amountTotal){
			footerData[key] = amountTotal[key]+'<br>'+moneyTotal[key].toFixed(2);
		}
		grid.footerData('set',footerData);
    },
	initGrid:function(){
		$("#grid").jqGrid('GridUnload');
		var colModel = [
	    	{label:'类别编号',name: 'tp_code',index:'tp_code',width:80,
	    		cellattr: function(rowId, tv, rawObject, cm, rdata) {return 'id=\'tp_code' + rowId + "\'";}},
	    	{label:'类别名称',name: 'tp_name',index:'tp_name',width:100,
	    		cellattr: function(rowId, tv, rawObject, cm, rdata) {return 'id=\'tp_name' + rowId + "\'";}},
	    	{label:'',name: 'child_type',index:'child_type',width:100,hidden:true},
	    	{label:'',name: 'tp_code_hid',index:'tp_code_hid',width:100,hidden:true},
	    	{label:'项目',name: 'project',index:'project',width:100}
	    ];
		if(selectShops != null && selectShops.length > 0){
			for (var i = 0; i < selectShops.length; i++) {
				colModel.push({label:selectShops[i].sp_name,name: selectShops[i].sp_code,index:'',width: 80,sortable:false,align:'right',formatter: handle.formatData});
			}
		}else{
			for (var i = 0; i < allShops.length; i++) {
				colModel.push({label:allShops[i].sp_name,name: allShops[i].sp_code,index:'',width: 80,sortable:false,align:'right',formatter: handle.formatData});
			}
		}
		colModel = colModel.concat([
			{label:'小计',name: 'total',index: 'total',width:70,align:"right",formatter: handle.formatData}
		]);
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:-1,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			scroll: 1,//是否滚动
			jsonReader: {
				root: 'data',
				repeatitems : false,
				id: 'id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
				THISPAGE.Merger2('tp_code');
				THISPAGE.Merger2('tp_name');
			},
			loadError: function(xhr, status, error){		
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				var tp_upcode = $("#tp_upcode").val();
				var rowData = $("#grid").jqGrid("getRowData", rowid);
				if(tp_upcode == rowData.tp_code_hid){
					Public.tips({type: 2, content : '当前页面已经是该类别的子级数据！'});
					return;
				}
				if(rowData.child_type == "" || rowData.child_type == rowData.tp_code_hid){
					Public.tips({type: 2, content : '无子类别或子类别无数据！'});
					return;
				}
				handle.queryChildType(rowData.tp_code_hid);
			}
	    });
	},
	Merger2:function(CellName){
    	var ids = $("#grid").getDataIDs();
        var length = ids.length;
        for (var i = 0; i < length; i++) {
            var before = $("#grid").jqGrid('getRowData', ids[i]);
            if(i%2 == 0){
            	$("#" + CellName + "" + ids[i] + "").attr("rowspan", 2);
            }else{
            	$("#grid").setCell(ids[i], CellName, '', { display: 'none' });
            }
        }
    },
	buildParams : function(){
		var params = '';
		params += 'tp_upcode='+$("#tp_upcode").val();
		params += '&bd_code='+$("#bd_code").val();
		params += '&pd_season='+$("#pd_season").val();
		params += '&pd_year='+$("#pd_year").val();
		params += '&pd_code='+$("#pd_code").val();
		if(selectShops.length > 0){
			params += '&shopCodes='+$("#shopCodes").val();
		}else{
			var sp_code = [];
			for (var i = 0; i < allShops.length; i++) {
				sp_code.push(allShops[i].sp_code);
			}
			params += '&shopCodes='+sp_code.join(",");
		}
		return params;
	},
	reset:function(){
		$("#pd_code").val("");
		$("#pd_name").val("");
		$("#bd_name").val("");
		$("#bd_code").val("");
		$("#span_pd_season").getCombo().selectByValue("");
		$("#span_pd_year").getCombo().selectByValue("");
		$("#shop_name").val("");
		$("#shopCodes").val("");
		selectShops = [];
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.initGrid();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.initGrid();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
	}
}
THISPAGE.init();